#include "FreeImage.h"
#include "Texture.h"

namespace TG
{
	Texture* Texture::load(const char* fileName)
	{
		FREE_IMAGE_FORMAT fifmt = FreeImage_GetFileType(fileName, 0);
		if (fifmt == FIF_UNKNOWN)
		{
			return  0;
		}
		FIBITMAP *dib = FreeImage_Load(fifmt, fileName, 0);
		FREE_IMAGE_COLOR_TYPE type = FreeImage_GetColorType(dib);

		FIBITMAP* temp = dib;
		dib = FreeImage_ConvertTo32Bits(dib);
		FreeImage_Unload(temp);

		BYTE* pixels = (BYTE*)FreeImage_GetBits(dib);
		int width = FreeImage_GetWidth(dib);
		int height = FreeImage_GetHeight(dib);

		//int pitch = width * 4;
		//BYTE* row = new BYTE[width * 4];
		//for (int j = 0; j < height / 2; j++)
		//{
		//	memcpy(row, pixels + j * pitch, pitch);
		//
		//	memcpy(pixels + j * pitch, pixels + (height - j - 1) * pitch, pitch);
		//
		//	memcpy(pixels + (height - j - 1) * pitch, row, pitch);
		//}
		//delete[]row;
		
		Texture* image = new Texture(width, height, pixels);
		FreeImage_Unload(dib);

		return  image;
	}

	Rgba Texture::getPixel(unsigned int x, unsigned int y)
	{
		return _pixel[y * _width + x];
	}

	Rgba Texture::getPixelUV(float u, float v)
	{
		int x = _width * u;
		int y = _height * v;

		return _pixel[y * _width + x];
	}
}